<?php
/**
 * minf - core library
 * modules/page.php
 *
 * @author per function || minf.org team
 * @version 0.beta4
 * @copyright no,no,left, minf.org, 25 February, 2009
 * @license GPL
 * @package default
 **/

class Page {
	public static $Vars;
	public static $Includeds;
	//public static $Html;
	
	public static function Set($varn, $val, $method=null) {
		// methods : append, set, add
		if (!is_string($varn)) return false;
		
		if (strpos($varn, ".")===false) {
			//if (!self::$Vars[$varn]) self::$Vars[$varn] = "";
			$toset = &self::$Vars[$varn];
		} else {
			$pt = explode(".", $varn);
			if (sizeof($pt)==2) $toset = &self::$Vars[$pt[0]][$pt[1]];
			elseif (sizeof($pt)==3) $toset = &self::$Vars[$pt[0]][$pt[1]][$pt[2]];
			elseif (sizeof($pt)==4) $toset = &self::$Vars[$pt[0]][$pt[1]][$pt[2]][$pt[3]];
		}
		
		if (!$method) {
			if (isset($toset)&&is_string($toset)) $method = "append";
			else $method = "set";
		}

		if ($method=="append") 
			$toset .= $val;
		elseif ($method=="prepend")
			$toset = $val.$toset;
		elseif ($method=="set")
			$toset = $val;
		elseif ($method=="add")
			if (is_array($toset)) $toset[] = $val;
				else $toset = array($toset, $val);
	}
	
	public static function JS($path) {
		$path = findFileURL($path, get_caller_class(2));
		if (is_array(self::$Includeds)&&sizeof(self::$Includeds)>=1) {
			if (!in_array($path, self::$Includeds)) self::$Includeds[] = $path;
			else return true;
		}else{
			self::$Includeds[] = $path;
		}
		self::Set("page.head", "<script src=\"$path\" type=\"text/javascript\" charset=\"utf-8\"></script>\n");
	}
	
	public static function CSS($path) {
		$path = findFileURL($path, get_caller_class(2));
		if (!in_array($path, self::$Includeds)) self::$Includeds[] = $path;
		else return true;
		self::Set("page.head", "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$path}\" />\n");
	}
	
	public static function Script ($code) {
		self::Set("page.script", $code);
	}
}

function findFileURL($path, $class = null) {
	global $conf, $cl;
	if (substr($path, 0, 1)!="/") {
		if ($class) $apppath = App::GetPath($class);
		if (file_exists(USER_PATH.substr($conf['userdir']['tpl'], 1)."/".$path)) return $cl['relurl'].$conf['userdir']['tpl']."/".$path;
		elseif ($class&&file_exists($apppath.$path)) return $cl['relurl']."/".substr($apppath, strlen(USER_PATH)).$path;
		else return $path;
	}else{
		return $path;
	}
}

function includeAllJS($path, $withcss = false) {
	global $cl;
	$upath = str_replace("//", "/", USER_PATH.$path);
	if (substr($path,-1)!="/") $path .= "/";
	$files = dirList($upath);
	if (!$files) return false;
	foreach ($files as $_file) {
		if (substr($_file,-2)=="js")
			Page::JS($cl['relurl'].$path.$_file);
		if ($withcss&&file_exists($upath."/".substr($_file,0,-2)."css"))
			Page::CSS($cl['relurl'].$path.substr($_file,0,-2)."css");
	}
	return true;
}

?>